package com.xiaolin.sports.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;

import com.xiaolin.sports.vo.ImageSynthesisVo;

public class ImageUtil {

	public static void composePic(String filesrc,String outsrc,List<ImageSynthesisVo> list, Integer width, Integer height) {
		try {
			File bgfile = new File(filesrc);
			Image bg_src = javax.imageio.ImageIO.read(bgfile);
			if(width == null) width = bg_src.getWidth(null);
			if(height == null) height = bg_src.getHeight(null);
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = tag.createGraphics();
			g2d.drawImage(bg_src, 0, 0, width, height, null);
			g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,1.0f)); //透明度设置开始 
			for(ImageSynthesisVo vo : list) {
				if(vo.getType().equals("image")) {
					URL url = new URL(vo.getFileUrl());
					HttpURLConnection conn = (HttpURLConnection)url.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(5 * 1000);
					InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
					Image logoSrc = javax.imageio.ImageIO.read(inStream);
					g2d.drawImage(logoSrc, vo.getPointX(), vo.getPointY(), vo.getWidth(), vo.getHeight(), null);     
					conn.disconnect();
					inStream.close();
				}else {
					// 设置字体、字型、字号  
					g2d.setFont(new Font("Serif", Font.BOLD, vo.getFontSize())); 
					g2d.setColor(Color.DARK_GRAY);
					g2d.drawString(vo.getText(), vo.getPointX(), vo.getPointY());
				}
			}
			g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); //透明度设置 结束
			FileOutputStream out = new FileOutputStream(outsrc);
			ImageIO.write(tag, "jpg", out);//写图片
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
